<?php

namespace App\Http\Controllers\Cruise\Web;

use App\Http\Controllers\BaseController;
use App\Service\Cruise\Disinfect\CruiseDisinfectService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Validation\ValidationException;

class CruiseDisinfectController extends BaseController
{

    /**
     * 获取文件内容
     */
    public function analyzeXlsx(Request $request): JsonResponse
    {
        $uploadedFile = $request->file('file');
        if (!$uploadedFile instanceof UploadedFile) {
            return $this->fail(400, '请上传文件');
        }

        // 限制文件大小 1MB
        if ($uploadedFile->getSize() > 1024 * 1024) {
            return $this->fail(400, '文件大小超过限制');
        }

        $allowed_extensions = ['csv', 'xlsx', 'Xlsx'];
        if (!in_array(strtolower($uploadedFile->getClientOriginalExtension()), $allowed_extensions)) {
            return $this->fail(400, '只能上传 ' . implode(',', $allowed_extensions) . ' 格式的文件.');
        }

        $data = CruiseDisinfectService::analyzeXlsx($uploadedFile);

        return $this->success($data);
    }


    /**
     * @throws ValidationException|GuzzleException
     */
    public function importTask(Request $request): JsonResponse
    {
        $this->validate($request, [
            'taskList'      => 'required|array',
            'templateId'    => 'required|integer|gt:0',
            'startDateTime' => 'required|string|date_format:Y-m-d',
            'endDateTime'   => 'required|string|date_format:Y-m-d',
            'name'          => 'required|string',
        ], [
            'taskList.required'         => '请传入任务',
            'taskList.array'            => '任务必须是数组',
            'templateId.gt'             => '请传入有效的任务模版',
            'startDateTime.date_format' => '日期格式错误',
            'endDateTime.date_format'   => '日期格式错误',
        ]);

        $taskList      = $request->post('taskList', []);
        $templateId    = (int)$request->post('templateId');
        $startDateTime = (string)$request->post('startDateTime');
        $endDateTime   = (string)$request->post('endDateTime');
        $name          = (string)$request->post('name');

        if (empty($taskList) || !collect($taskList)->where('businessStatus', true)->count()) {
            return $this->fail(400, '导入任务数为空');
        }

        $data = CruiseDisinfectService::addImportTask($taskList, $templateId, $startDateTime, $endDateTime, $name);
        return $this->success($data);
    }
}